﻿var me = this,
    draftId = PAI.Global.getUrlData('draftId'),
    controller = this.lookupController(),
    vm = this.lookupViewModel();
//默认显示作废按钮
vm.set('NebulogyForm.isShowCancel', 'true');
//默认显示召回按钮
vm.set('NebulogyForm.isShowRecall', 'true');
//流程状态默认是normal
vm.set('NebulogyForm.isProcessstate', 'normal');
vm.set('NebulogyForm.emailapplicantId', PAI.Global.getAccount().employee.id);
//定义变量存储申请人姓名
var name = requestData.bizModel.GeneralInformation.Applicant;
this.lookupViewModel().set('NebulogyForm.emailapplicantName', name);
//默认给变量赋值
vm.set('NebulogyForm.nodeName', '');
//如果采购邮箱为空，
if (Ext.isEmpty(requestData.bizModel.purchasingEmail)) {
    vm.set('NebulogyForm.purchasingEmail', '');
}
//如果采购上级邮箱为空，
if (Ext.isEmpty(requestData.bizModel.emailReporTo)) {
    vm.set('NebulogyForm.emailReporTo', '');
}
//如果抄送为空
if (Ext.isEmpty(requestData.bizModel.ccpeopleid)) {
    vm.set('NebulogyForm.ccpeopleid', '');
}
vm.set('NebulogyForm.processState', 0);
//vm.set('NebulogyForm.purchasingEmail', '');
vm.set('NebulogyForm.isInquiryCall', 0);
vm.set('NebulogyForm.isCopyMe', 0);
requestData.bizModel.isInquiryCall = 0;
//获取申请人直接
vm.set('NebulogyForm.employeesRank', PAI.Global.getAccount().employee.ext_jlrJobGrade);

//判断流程是否需要走并行流程
if (requestData.bizModel.CompanyAllocation) {
    var list = requestData.bizModel.CompanyAllocation;
    var companyJLRC = 0;
    var companyCJLR = 0;
    var JLRCAmount = 0;
    var CJLRAmount = 0;
    for (var i = 0; i < list.length; i++) {
        if ((list[i].Company == "JLRC" || list[i].Company == "LRE")) {
            if (list[i].CompanySharingRatio == 100) {
                companyJLRC += 1;
            }
            JLRCAmount = floatAdd(JLRCAmount, list[i].Cost);
        } else if (list[i].Company == "JLRC") {
            if (list[i].CompanySharingRatio == 100) {
                companyCJLR += 1;
            }
            JLRCAmount = floatAdd(JLRCAmount, list[i].Cost);
        }
    }
    //并行的参数(1:JLRC,2:CJLR,3:Shared)
    if (companyJLRC > 0 && companyCJLR == 0) {
        vm.set('NebulogyForm.companySection.company', '1');
    }
    else if (companyJLRC == 0 && companyCJLR > 0) {
        vm.set('NebulogyForm.companySection.company', '2');
    }
    else {
        vm.set('NebulogyForm.companySection.company', '0');
    }
    //给Amount赋值
    vm.set('NebulogyForm.amount.JLRCAmount', JLRCAmount);
    vm.set('NebulogyForm.amount.CJLRAmount', CJLRAmount);
}

//发起时，把多选框中已勾选的值拼接赋值给SpecialApprovers1
var SpecialApprovers1 = [];

Ext.each(ref.SpecialApprovers.items.items, function (ctr) {
    if (ctr.checked) {
        SpecialApprovers1.push(ctr.boxLabel);
    }
});

vm.set('NebulogyForm.speical.HaveSpecialApprovers1', SpecialApprovers1.length > 0 ? 'yes' : 'no');
vm.set('NebulogyForm.speical.SpecialApprovers1', '"' + SpecialApprovers1.join('","') + '"');

var expenseType = ref.ExpenseType.getValue();
var prType = ref.PRType.getValue();
var companyC = ref.companyC.getValue();

vm.set('NebulogyForm.totalNetAmount', requestData.bizModel.totalAmountList.pi1);
vm.set('NebulogyForm.totalGrossAmount', requestData.bizModel.totalAmountList.tga1);

//满足抄送采购条件
if (expenseType != '5') {
    vm.set('NebulogyForm.isCopyMe', 0);
    vm.set('NebulogyForm.oldpurchasingId', requestData.bizModel.purchasingId);
} else {
    vm.set('NebulogyForm.isCopyMe', 1);
    vm.set('NebulogyForm.oldpurchasingId', '');
}

//Tooling 提交的时候获取PA 对应的UK
if (expenseType == '5') {
    var store2 = ref.datagrid2.getStore();
    var paList = [];

    if (store2.data.length) {
        Ext.each(store2.data.items, function (item) {
            paList.push(item.get('ProjectActivity'));
        });

        Ext.PAIRest.request({
            ns: PAI.application.url,
            url: 'last/dictItemObj/customQuery',
            method: "POST",
            async: false,
            data: {
                "fields": [
                    { "name": "id" },
                    {
                        "exp": "$." + PAI.Global.getLanguage(),
                        "name": "name",
                        "type": "json"
                    },
                    { "name": "code" },
                    { "name": "orderIndex" }
                ],
                filter: "t1.pId='a65986df-3037-434f-8825-5db6ebd6fded'"
            },
            success: function (result) {
                if (result.responseCode == '100') {
                    var ukApprovers = [];
                    Ext.each(result.data, function (rec) {
                        if (Ext.Array.contains(paList, rec.name)) {
                            ukApprovers.push(rec.code);
                        }
                    });
                    vm.set('NebulogyForm.toolingUKApprovers', ukApprovers.join(','));
                }
            }
        });
    }
}
var SubTotal = 0;
var purStore = ref.datagrid2.getStore();

//根据PurchaseItems中NetPrice总和，赋值给SubTotal
for (var i = 0; i < purStore.getCount(); i++) {
    var TotalPrice = purStore.getAt(i).data.TotalPrice;
    SubTotal = floatAdd(SubTotal, TotalPrice);
}
vm.set('NebulogyForm.amount.SubTotal', SubTotal);
//保存Company Alloction 金额
var temp = {};
var store3 = ref.datagrid3.getStore();
for (var i = 0; i < store3.data.items.length; i++) {
    var currentData = store3.data.items[i].data;
    if (null != temp[currentData.Company] || undefined != temp[currentData.Company]) {
        temp[currentData.Company] = temp[currentData.Company] + currentData.Cost;
    } else {
        temp[currentData.Company] = currentData.Cost;
    }
}
vm.set('NebulogyForm.amount.CompanySubTotal', temp);

//所有的验证都通过了.还需要把采购Item的金额最新的TotalPrice 赋值给originalTotalPrice.这样下次Enquiry后的页面记录的originalTotalPrice就是当前最新的值.
Ext.each(purStore.data.items, function (record) {
    record.set('originalTotalPrice', record.get('TotalPrice'));
});

//加法运算
function floatAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}


function getFileIds(list) {
    return (list || []).reduce(function (item, next) {
        item.push(next.fileObjId);
        return item;
    }, []).join();
}

requestData.bizModel.attachmentsFileIds = getFileIds(requestData.bizModel.file8);
requestData.bizModel.ukCrossChargeAttachmentsFileIds = getFileIds(requestData.bizModel.file7);
